package com.pat.jrgwt.client;

import java.util.Date;

import com.google.gwt.event.dom.client.ChangeHandler;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.pat.jrgwt.shared.MyConstants;

public class YearSelector extends Composite
{

    public ChangeHandler OnYearChanged = null;
    
    protected ListBox m_lstYears = new ListBox();
    
    protected int m_selectedYear = 0;
    
    @SuppressWarnings("deprecation")
    public YearSelector()
    {
        m_selectedYear = new Date().getYear() + 1900; 
        init(m_selectedYear);
    }
    
    public YearSelector(int startYear)
    {
        m_selectedYear = startYear;
        init(startYear);
    }
    
    public void addYearChangeHandler(ChangeHandler handler)
    {
        m_lstYears.addChangeHandler(handler);
    }
    
    protected void init(int startYear)
    {
        VerticalPanel panel = new VerticalPanel();
        formatYears(startYear, MyConstants.TOTAL_YEARS);
        panel.add(m_lstYears);
        
        // Component must call this method
        initWidget(panel);
    }

    protected void formatYears(int startYear, int totalYears)
    {
        for (int i = 0; i < totalYears; i++)
        {
//            int year = 1900 + totalYears - i;
            m_lstYears.addItem("" + (startYear - i));
            if( startYear - i == m_selectedYear )
            {
                m_lstYears.setSelectedIndex(i);
            }
        }
    }

    public int getSelectedYear()
    {
        m_selectedYear = Integer.parseInt(m_lstYears.getItemText(m_lstYears.getSelectedIndex()));
        return m_selectedYear;
    }

}
